﻿using System;
using System.Windows.Data;
using System.Globalization;
using System.Resources;
using System.Collections.Generic;
using System.Collections;

namespace CodeCounsel.SharePoint.RibbonDesigner.View.TypeConverters
{
    class ResourceConverter
        : IValueConverter
    {
        static Dictionary<string, Dictionary<string ,string>> _resources;

        static ResourceConverter()
        {
            _resources = new Dictionary<string, Dictionary<string, string>>();
        }

        public object Convert(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            string resourceIdentifier = (string)value;
            try
            {
                if (IsResourceIdentifier(resourceIdentifier))
                {
                    resourceIdentifier = resourceIdentifier.TrimEnd(';');
                    string resourcePair = resourceIdentifier.Substring(resourceIdentifier.IndexOf(':') + 1);
                    string[] resource = resourcePair.Split(',');
                    string filename = resource[0];
                    filename = filename.ToLower();
                    string resourceID = resource[1];
                    if (_resources.ContainsKey(filename.ToLower()) == false)
                    {
                        ResXResourceReader reader = new ResXResourceReader(
                            @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Resources\" + filename + ".resx");
                        Dictionary<string, string> values = new Dictionary<string, string>();
                        foreach (DictionaryEntry o in reader)
                        {
                            values.Add((string)o.Key, (string)o.Value);
                        }
                        _resources.Add(filename, values);
                    }
                    Dictionary<string, string> items = _resources[filename];
                    return items.ContainsKey(resourceID) ?
                        items[resourceID] : resourceID;
                }
            }
            catch { }
            return resourceIdentifier;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        bool IsResourceIdentifier(string resourceIdentifier)
        {
            return resourceIdentifier != null && resourceIdentifier.StartsWith("$Resources", StringComparison.OrdinalIgnoreCase);
        }
    }
}
